package com.sunday.authorization.mock.oauth2.client.web;

import lombok.RequiredArgsConstructor;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.reactive.function.client.WebClient;

import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient;

@RequiredArgsConstructor
@Controller
public class OAuthClientController {

    private final WebClient webClient;


    /**
     * 客户端模式示例
     * @param model
     * @param authorizedClient
     * @return
     */
    @ResponseBody
    @GetMapping("clientSecretBasic")
    public Object clientSecretBasic(Model model, @RegisteredOAuth2AuthorizedClient("clientSecretBasic") OAuth2AuthorizedClient authorizedClient) {
        System.out.println("登录成功!");
        String result = webClient.get().uri("http://localhost:8060/message/msg")
                .attributes(oauth2AuthorizedClient(authorizedClient))
                .retrieve() //从这个方法以后就开始处理http响应了
                .bodyToMono(String.class)
                .block();
        return STR."\{result}<br/>\{authorizedClient.getAccessToken()}";
    }

    /**
     * 客户端模式示例
     * @param model
     * @param authorizedClient
     * @return
     */
    @ResponseBody
    @GetMapping("clientSecretPost")
    public Object clientSecretPost(Model model, @RegisteredOAuth2AuthorizedClient("clientSecretPost") OAuth2AuthorizedClient authorizedClient) {
        System.out.println("登录成功!");
        String result = webClient.get().uri("http://localhost:8060/message/msg")
                .attributes(oauth2AuthorizedClient(authorizedClient))
                .retrieve() //从这个方法以后就开始处理http响应了
                .bodyToMono(String.class)
                .block();
        return STR."\{result}<br/>\{authorizedClient.getAccessToken()}";
    }


}
